# -*-coding:utf-8-*-
from time import sleep
import urllib3
import requests, json
# from public.script_function import *
import datetime, json, re, jsonpath

from backend.encryption.Lyzd_java_decrypt import JAVACommon


# def echo(*args):  # 不限数量的单值参数,请求链接后等到的响应信息没有转换成json格式，记录每条数据创建时间及信息；
#     for i in args:
#         print(
#             "[time:{asctime}] - INFO : {message}".format(asctime=datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
#                                                          message=i))
#

class Http:
    def __init__(self, model):
        self.model = model

    def __request(self, **kwargs):
        if self.model.lower() == "get":
            response = requests.request("get", kwargs["url"], params=kwargs["params"], headers=kwargs["headers"])
            # print(response.text)
        # post的参数名要为data
        elif self.model.lower() == "put":
            # 转换成字符串传入
            params = json.dumps(kwargs["params"], ensure_ascii=False).encode()
            response = requests.request("put", kwargs["url"], data=params, headers=kwargs["headers"])
        elif self.model.lower() == "delete":
            # 转换成字符串传入
            params = json.dumps(kwargs["params"], ensure_ascii=False).encode()
            response = requests.request("delete", kwargs["url"], data=params, headers=kwargs["headers"])
        elif self.model.lower() == "postbody":

            print("开始")
            print(kwargs["url"])
            print(kwargs["params"])
            print(type(kwargs["params"]))
            print(kwargs)
            headers = kwargs["headers"]
            print(headers)
            url_list = kwargs["url"].split(":", 1)
            print(url_list)
            print("####################################33")




            # 需要根据接口字段传值来判断
            if url_list[0] == 'https':
                print("1")
                headers['User-Agent'] = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.82 Safari/537.36"

                try:
                    if headers == {'Content-Type': 'application/json'}:
                        params = json.dumps(kwargs["params"],ensure_ascii=False).encode()  # 字典->字符串 ascii 字符码 + 编码（默认utf-8）；
                        print("转换json:%s" % params)
                    else:
                        params = kwargs["params"]
                except:
                    print("传请求头参数有误，添加异常处理")
                    pass

            elif url_list[0] == 'http':
                print("2")
                try:
                    if headers['Content-Type'] ==  'application/json':
                        print("3")
                        params = json.dumps(kwargs["params"],ensure_ascii=False).encode()  # 字典->字符串 ascii 字符码 + 编码（默认utf-8）；
                        print("转换json:%s" % params)
                    else:
                        print("4")
                        params = kwargs["params"]
                except:
                    print("5")
                    print("传请求头参数有误，添加异常处理")
                    pass

            else:
                print("传递请求协议有误，添加异常处理")
                pass

            # requests.packages.urllib3.disable_warnings()
            print("执行啦")
            print(params)
            print(type(params))
            print(headers)
            print(kwargs["url"])

            response = requests.request("post", kwargs["url"], data=params, headers=headers, verify=False)



        elif self.model.lower() == "postform":
            response = requests.request("post", kwargs["url"], data=kwargs["params"], headers=kwargs["headers"])
        elif self.model.lower() == "postfile":
            response = requests.request("post", kwargs["url"], data=kwargs["params"], headers=kwargs["headers"],
                                        files=kwargs["files"])

        return response

    # 文本转换成json字符串
    def __changeJson(self, response, **kwargs):
        try:
            responseJson = json.loads(response.text)
            return responseJson
        except:
            # 返回值非json格式
            print("返回值非json格式")
            responseJson = response.text
            return responseJson






    def __call__(self, fuc):
        def wrapper(*args, **kwargs):
            fuc(*args, **kwargs)
            response = self.__request(**kwargs)
            responseJson = self.__changeJson(response, **kwargs)
            return responseJson, response.status_code

        return wrapper


@Http(model="GET")
def get(url, params, headers):
    pass


@Http(model="PUT")
def put(url, params, headers):
    pass


@Http(model="DELETE")
def delete(url, params, headers):
    pass


@Http(model="POSTFORM")
def postform(url, params, headers):
    pass


@Http(model="POSTBODY")
def postbody(url, params, headers):
    pass


@Http(model="POSTFILE")
def postfile(url, params, headers, files):
    pass


def http(method, url, params, headers):
    #  1.根据请求头及请求方式进行判断

    if method == "POST":
        if headers['Content-Type'] == 'application/json' or headers['Content-Type'] == 'application/xml' :
            print(url)
            print(params)
            print(headers)

            return  postbody(url=url, params=params, headers=headers)

        else:
            return postform(url=url, params=params, headers=headers)

    elif method == "GET":
        return get(url=url, params=params, headers=headers)
    elif method == "PUT":
        return put(url=url, params=params, headers=headers)
    elif method == "DELETE":
        return delete(url=url, params=params, headers=headers)

    else:
        pass


